import { Button, Form, message } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import { fn } from 'src/services/api/variable';
import { randomKey } from '../../../utils/utils';
import FnConfig from './config';
import FnParams from './params';
import './style.less';
import { connect } from 'react-redux';
const DefaultValue = {
  params: [
    {
      // 加入ukey
      key: randomKey(),
      name: '',
      type: '',
      isNull: 1,
      remark: '',
      showType: 1,
    },
  ],
  name: '',
  code: '',
  remark: '',
  returnType: '',
  status: 1,
  script: '',
  isReturn: 1,
  useScope: [],
};
function FnAdd(props) {
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState(DefaultValue);
  const fnParamsRef = useRef();
  useEffect(() => {
    if (props.record && props.record.id && !props.isAuditLog) {
      fn.detail({ id: props.record.id }).then((res) => {
        setFormData(res.data);
      });
    }
    if (props.value && Object.keys(props.value).length > 0) {
      setFormData(props.value);
    }
  }, []);

  const vad = () => {
    return new Promise((res, rej) => {
      props.form.validateFieldsAndScroll((err, vals) => {
        if (err) {
          setLoading(false);
        }
        err ? rej() : res();
      });
    });
  };

  const handleCancel = () => {
    props.closeModal();
  };
  const handleSubmit = async (evt) => {
    console.log('???');
    evt.preventDefault();
    try {
      setLoading(true);
      await vad();
      const fd = props.form.getFieldsValue();

      fd.useScope = fd.useScope;
      const ps = fnParamsRef.current.getPs();
      ps.forEach((item, index) => {
        if (fd.params[index].showType === 1 && !item.varTypeLimit) {
          message.warning('配置参数输入范围不能为空');
          throw '配置参数输入范围不能为空';
        }
        if ((fd.params[index].showType === 2 || fd.params[index].showType === 3) && item.varEnums.length === 0) {
          message.warning('配置参数枚举值不能为空');
          throw '配置参数枚举值不能为空';
        }
      });
      const save = props.record ? fn.update : fn.add;

      const params = (fd.params || []).map((o, index) => {
        return {
          ...o,
          code: 'p' + (index + 1),
          varEnums:
            o.showType === 2 || o.showType === 3
              ? ps[index].varEnums.map((it) => {
                  const { id, ...rest } = it;
                  return {
                    ...rest,
                  };
                })
              : [],
          varTypeLimit: o.showType === 1 ? ps[index].varTypeLimit : [],
        };
      });
      const { code, ...rest } = fd;
      const pp = props.record
        ? {
            ...rest,
            params,
            id: props.record.id,
          }
        : {
            ...fd,
            params,
          };
      const res = await save(pp);
      if (res.code === '0') {
        message.success(res.msg);
        props.closeModal();
      } else {
        message.error(res.msg);
      }
    } catch {}
    setLoading(false);
  };

  return (
    <div>
      <Form autoComplete='off' onSubmit={() => false}>
        <div className='p30p20'>
          <FnParams
            {...props}
            form={props.form}
            value={formData.params}
            ref={fnParamsRef}
            compareData={(props.compareData && props.compareData.params) || []}
          />
          <br />
          <FnConfig {...props} form={props.form} value={formData} />
        </div>
        <div className='tantuer-form'>
          {props.actionType !== 'detail' && (
            <div className='form-btn'>
              <Button className='marr10' onClick={handleCancel}>
                取消
              </Button>
              <Button type='primary' onClick={handleSubmit} loading={loading} autoFocus={true}>
                确定
              </Button>
            </div>
          )}
        </div>
      </Form>
    </div>
  );
}

const mapStateToProps = (state) => {
  return {
    use_scope: state.code.use_scope || [],
    func_param_limit_scope: state.code.func_param_limit_scope || [],
  };
};

export default connect(mapStateToProps)(Form.create()(FnAdd));
